package presenter.rename;

import main.InputBean;
import utils.OnLogListener;
import utils.FileBean;
import utils.FileFilter;
import utils.TextUtils;

import java.io.File;
import java.util.*;

/**
 * 文件命名
 */
public class FileRenamer {
    private final InputBean info;
    private final String path1;
    private List<FileBean> items;
    private final Map<String, String> pairs = new HashMap<>();
    private final OnLogListener logger;
    private final RenameType renamer;

    public static void parse(InputBean info, OnLogListener listener) {
        new FileRenamer(info, listener);
    }

    private FileRenamer(InputBean info, OnLogListener logger) {
        this.info = info;
        this.path1 = info.path1();
        this.logger = logger;
        this.renamer = RenameType.parse(info.mode().tag());
        log("任务开始!");
        try {
            collect(() -> filter(() -> rename(logger::taskFinish)));
        } catch (Exception ex) {
            log("异常:" + ex.getMessage());
            logger.taskFinish();
        }
    }

    private void collect(Runnable next) {
        List<FileBean> items = FileFilter.filter(false, path1, name -> {
            String path2 = info.path2();
            if (TextUtils.isEmpty(path2)) {
                return true;
            } else {
                return name.contains(path2);
            }
        });
        if (items == null || items.isEmpty()) {
            log("文件夹为空!");
            logger.taskFinish();
        } else {
            this.items = items;
            next.run();
        }
    }

    private void filter(Runnable next) {
        for (FileBean bean : items) {
            if (renamer.needReName(info, bean)) {
                renamer.reName(info, bean, pairs);
            } else {
                log(bean.path() + "  不需要重命名.");
            }
        }
        next.run();
    }

    private void rename(Runnable next) {
        Set<Map.Entry<String, String>> entries = pairs.entrySet();
        for (Map.Entry<String, String> item : entries) {
            String from = item.getKey();
            String to = item.getValue();
            if (!TextUtils.isEmpty(from) && !TextUtils.isEmpty(to)) {
                rename(from, to);
            } else {
                log("出现空的情况:" + from + "|" + to);
            }
        }
        next.run();
    }

    private void rename(String from, String to) {
        File file = new File(from);
        if (file.exists()) {
            FileBean bean = FileBean.newInstance(file);
            bean.move(to, new OnLogListener() {
                @Override
                public void log(String content) {
                    FileRenamer.this.log(content);
                }

                @Override
                public void taskFinish() {

                }
            });
        } else {
            log("该文件不存在:" + from);
        }
    }

    private void log(String content) {
        logger.log(content);
    }
}
